package com.xiaou.qrcodedemo.controller;

import com.xiaou.qrcodedemo.utils.QRCodeGenerator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
public class QRCodeController {

    @PostMapping("/qrcode/gen")
    public void generateQRCode(
            @RequestParam String url,
            @RequestParam String type,
            @RequestParam(required = false) MultipartFile logo,
            @RequestParam(required = false) MultipartFile bgImg,
            HttpServletResponse response) throws IOException {

        // 确保 URL 不为空
        if (url == null || url.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "URL cannot be empty");
            return;
        }

        try {
            switch (type) {
                case "black":
                    QRCodeGenerator.generateBlackAndWhiteQRCode(url, response);
                    break;
                case "logo":
                    QRCodeGenerator.generateQRCodeWithLogo(url, response, logo.getInputStream());
                    break;
                case "color":
                    QRCodeGenerator.generateColorQRCode(url, response);
                    break;
                case "background":
                    QRCodeGenerator.generateBackgroundImageQRCode(url, response, bgImg.getInputStream());
                    break;
                case "shape":
                    QRCodeGenerator.generateSpecialShapeQRCode(url, response);
                    break;
                case "imageFill":
                    QRCodeGenerator.generateImageFilledQRCode(url, response, logo.getInputStream());
                    break;
                case "gif":
                    QRCodeGenerator.generateGifQRCode(url, response, bgImg.getInputStream());
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid QR code type");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating QR code");
        }
    }
}


